# -*- coding:utf-8 -*-
"""
@Author : 审心
@Time : 2023/5/6 15:47
"""
from dataclasses import dataclass

import pyautogui
from DrissionPage import WebPage
from DrissionPage.action_chains import ActionChains
from DrissionPage.commons.keys import Keys
from xlwings import Sheet
from common.logger.log import log_
import autoTask.taobao.sycm.xgfx.CacheAction as cache_action
from common.utils import ObjUtil, ExcelUtil, web_page_util
from common.utils.web_page_util import Input, Tap, MockTap

# 表格标题
excel_title = ["关键词", "日期", "搜索人数", "搜索次数", "点击率", "点击人数",
               "点击次数", "交易金额", "支付转化率",
               "在线商品数", "商城点击占比", "直通车参考价",
               "支付人数", "客单价", "搜索人数/在线商品数",
               "交易金额/在线商品数", "访客平均价值",
               "商品平均价值", "商品访客竞争度",
               "优质价值词", "竞争度", "预估转化件数",
               "平均交易指数"]

@dataclass
class AppendXgfxDataAction:
    """
    对结果表格的 sheet 页追加数据操作 \n
    Attributes:
        sheet : 结果表格 sheet 对象 \n
        date_cycle : 数据周期 7天 或 30天 \n
        p : 操作网页对象 \n
    """
    sheet: Sheet
    date_cycle: str
    p: WebPage

    def __call__(self):
        # 需要追加的数据行 以 元组为元素 (行号, 需要补充的数据)
        append_rows = []
        # 得到需要补充数据的关键词
        key_tuple_list = self.get_key_word()
        # 获取需要补充的数据 添加到列表中
        for key_map in key_tuple_list:
            # 从缓存中获取
            log_.info(f"尝试从缓存中获取 关键词 [{key_map[1]}] 相关分析数据")
            key_data = cache_action.get_one(key_map[1], "30天")
            if key_data:
                append_row = (key_map[0], key_data[2:])
            # 从页面中获取
            else:
                log_.info(f"尝试从页面中获取 关键词 [{key_map[1]}] 相关分析数据")
                append_row = (key_map[0], self.get_data_by_view(key_map[1]))
            if ObjUtil.is_empty(append_row):
                log_.warning(f"关键词 : {key_map[1]} 相关分析数据获取失败")
                continue
            append_rows.append(append_row)
        log_.info("获取关键词相关分析数据完毕")
        # 追加数据
        self.append_action(append_rows)

    def go_to_web_action_view(self):
        """
        跳转到获取关键词搜索分析的操作页面
        """
        if not self.p.url.startswith("https://sycm.taobao.com/mc/mq/search_analyze?activeKey=relation"):
            MockTap(self.p("x://span[.='市场']"), "跳转到市场界面失败", after_delay=(1, 3))()
            self.p.wait.load_complete(30)
            MockTap(self.p("x://span[.='搜索分析']"), "跳转到搜索分析界面失败", after_delay=(1, 3))()
            self.p.wait.load_complete(30)
            Input(self.p("c:.ant-input[placeholder='请输入搜索词，进行深度分析']"),
                  "对搜索框输入[店]失败", vals="店", after_delay=(2, 4))()
            web_page_util.set_page_active(self.p)
            pyautogui.press('enter')
            MockTap(self.p(
                "x://span[@class='oui-tab-switch']/span[@class='oui-tab-switch-item']/span[contains(.,'相关分析')]"),
                "点击跳转到相关分析页失败", after_delay=(1, 3))()
            date_ele = self.p(f"t:span@@text():{self.date_cycle}")
            if not date_ele and self.date_cycle == "30天":
                self.date_cycle = "7天"
                date_ele = self.p(f"t:span@@text():{self.date_cycle}")
            MockTap(date_ele, f"点击设置数据周期为{self.date_cycle}失败", after_delay=(1, 3))()
            web_page_util.wait_ele_disappear(self.p, ".oui-dt-message-content oui-dt-message-content-hasMask", 15)

    def get_key_word(self) -> list[tuple[int, str]]:
        """
        获取需要补充关键词数据
        :return: 元组列表 (sheet页行号,关键词字符串)
        """
        use_col = ExcelUtil.xw_get_last_used_column(self.sheet, 2)
        use_row = ExcelUtil.xw_get_has_content_row(self.sheet)
        r = self.sheet.range(f"A3:A{use_row}")
        ExcelUtil.sort_sheet_by_column(self.sheet.range(f"A3:{use_col}{use_row}"),
                                       lambda row_item: len(row_item[0]))
        result = []
        for row in r.rows:
            result.append((row.row, row[0].value))
        return result

    def get_data_by_view(self, search_key: str) -> list:
        """
        从页面种获取数据
        :param search_key: 搜索输入的关键词
        :return:
        """
        result = []
        # 前往首页
        self.go_to_web_action_view()
        Input(self.p("c:.ant-input[placeholder='请输入搜索词，进行深度分析']"),
              f"对搜索框输入 {search_key} 失败",
              vals=search_key, after_delay=(1, 3))()
        web_page_util.set_page_active(self.p)
        pyautogui.press('enter')
        web_page_util.wait_ele_disappear(self.p, ".oui-dt-message-content oui-dt-message-content-hasMask",
                                         15)
        Tap(self.p("t:span@text():小旺神一键转化"), "点击一键转化失败", before_delay=(1, 3),
            after_delay=(1, 3))()
        if self.p("x://span[@class='el-pagination__total']", timeout=10):
            Tap(self.p("x://button[contains(.,'一键复制')]"), before_delay=(1, 3), after_delay=(2, 3))()
            df = ExcelUtil.pd_paste_2_csv()
            # 存入缓存
            if not df.empty:
                cache_action.put_cache_by_df(search_key, "30天", df)
            save_cache_do = df.loc[df['关键词'] == search_key, '搜索人数':]
            if not save_cache_do.empty:
                result = list(save_cache_do.iloc[0].to_list())
        ActionChains(self.p).key_down(Keys.ESCAPE)
        return result

    def append_action(self, append_rows: list):
        """
        追加相关分析数据至表格
        :param append_rows: 需要追加的行数据
        :return:
        """
        if ObjUtil.is_empty(append_rows):
            return
        # 先插入追加数据的表头
        self.sheet.range('K2').options(insert='right').value = excel_title[2:]
        for row in append_rows:
            self.sheet.range(row[0], 11).value = row[1]
            # 自动调整所有单元格的行高和列宽
        self.sheet.autofit()
        log_.info("补充关键词相关分析至表格完毕")
